/**
     * API客户端工具，提供非Hook环境下的API请求功能
     */

    // API基础URL配置
    const API_BASE_URL = process.env.NODE_ENV === 'production' 
      ? 'https://api.example.com/v1' 
      : 'http://localhost:5000/api/v1';

    /**
     * 发送请求的通用方法
     * @param {string} endpoint - API端点
     * @param {Object} options - fetch选项
     * @returns {Promise<any>} 响应数据
     */
    const sendRequest = async (endpoint, options = {}) => {
      try {
        // 添加默认headers
        const headers = {
          'Content-Type': 'application/json',
          ...options.headers,
        };

        // 从localStorage获取token（如果有）
        const token = localStorage.getItem('authToken');
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }

        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
          ...options,
          headers,
        });

        // 处理非2xx响应
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || `请求失败: ${response.status}`);
        }

        // 解析响应
        const data = await response.json();
        return data;
      } catch (err) {
        console.error(`API请求错误 (${endpoint}):`, err);
        throw err;
      }
    };

    /**
     * GET请求
     * @param {string} endpoint - API端点
     * @param {Object} options - 额外的fetch选项
     * @returns {Promise<any>} 响应数据
     */
    const get = (endpoint, options = {}) => {
      return sendRequest(endpoint, {
        method: 'GET',
        ...options,
      });
    };

    /**
     * POST请求
     * @param {string} endpoint - API端点
     * @param {Object} data - 要发送的数据
     * @param {Object} options - 额外的fetch选项
     * @returns {Promise<any>} 响应数据
     */
    const post = (endpoint, data, options = {}) => {
      return sendRequest(endpoint, {
        method: 'POST',
        body: JSON.stringify(data),
        ...options,
      });
    };

    /**
     * PUT请求
     * @param {string} endpoint - API端点
     * @param {Object} data - 要发送的数据
     * @param {Object} options - 额外的fetch选项
     * @returns {Promise<any>} 响应数据
     */
    const put = (endpoint, data, options = {}) => {
      return sendRequest(endpoint, {
        method: 'PUT',
        body: JSON.stringify(data),
        ...options,
      });
    };

    /**
     * DELETE请求
     * @param {string} endpoint - API端点
     * @param {Object} options - 额外的fetch选项
     * @returns {Promise<any>} 响应数据
     */
    const del = (endpoint, options = {}) => {
      return sendRequest(endpoint, {
        method: 'DELETE',
        ...options,
      });
    };

    /**
     * 上传文件
     * @param {string} endpoint - API端点
     * @param {FormData} formData - 包含文件的FormData对象
     * @param {Function} progressCallback - 进度回调函数
     * @returns {Promise<any>} 响应数据
     */
    const uploadFile = async (endpoint, formData, progressCallback = null) => {
      try {
        // 从localStorage获取token（如果有）
        const token = localStorage.getItem('authToken');
        const headers = {};
        
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }

        // 使用XMLHttpRequest来支持进度监控
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          
          xhr.open('POST', `${API_BASE_URL}${endpoint}`);
          
          // 设置headers
          if (token) {
            xhr.setRequestHeader('Authorization', `Bearer ${token}`);
          }
          
          // 监听进度事件
          if (progressCallback) {
            xhr.upload.onprogress = (event) => {
              if (event.lengthComputable) {
                const percentComplete = Math.round((event.loaded / event.total) * 100);
                progressCallback(percentComplete);
              }
            };
          }
          
          xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
              const response = JSON.parse(xhr.responseText);
              resolve(response);
            } else {
              reject(new Error(`上传失败: ${xhr.status}`));
            }
          };
          
          xhr.onerror = function() {
            reject(new Error('网络错误'));
          };
          
          xhr.send(formData);
        });
      } catch (err) {
        console.error('文件上传错误:', err);
        throw err;
      }
    };

    // 导出API客户端
    const apiClient = {
      get,
      post,
      put,
      delete: del,
      uploadFile,
    };

    export default apiClient;
